package com.visikard.widget;

import java.util.Calendar;

import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.util.Log;
import android.widget.DatePicker;

import com.visikard.ui.fragment.SetTimeParent;

public class DatePickerFragment extends DialogFragment implements
DatePickerDialog.OnDateSetListener{
	
	private static long TIME_MIN = 0;
	private static long TIME_MAX = 0;

	SetTimeParent mParent;
	boolean isNextDate;
	boolean notSetMaxBackDate;

	public void setParent(SetTimeParent parent, long timeMin, long timeMax, boolean isNextDate) {
		this.mParent = parent;
		this.isNextDate = isNextDate;
		this.TIME_MIN = timeMin;
		this.TIME_MAX = timeMax;
		
	}

	@SuppressLint("NewApi")
	@Override
	public Dialog onCreateDialog(Bundle savedInstanceState) {
		// Use the current date as the default date in the picker
		final Calendar c = Calendar.getInstance();
		int year = c.get(Calendar.YEAR);
		int month = c.get(Calendar.MONTH);
		int day = c.get(Calendar.DAY_OF_MONTH);

		// load selected date if any
		String tmpday = "";
		if(isNextDate)
			tmpday = mParent.getNextdayStr();
		else
			tmpday = mParent.getBackdayStr();
			
		Log.i("NghiDo", "date = " + tmpday);
		if (tmpday.length() > 0 && tmpday.split("-").length == 3) {
			String[] tmp = tmpday.split("-");
			year = Integer.parseInt(tmp[0]);
			month = Integer.parseInt(tmp[1]) - 1;
			day = Integer.parseInt(tmp[2]);
		}

		// Create a new instance of DatePickerDialog and return it
		DatePickerDialog datePickerDialog = new DatePickerDialog(
				getActivity(), this, year, month, day);
		if(Build.VERSION.SDK_INT > Build.VERSION_CODES.GINGERBREAD_MR1){
			datePickerDialog.getDatePicker().setCalendarViewShown(false);
			
			if (Build.VERSION.SDK_INT > Build.VERSION_CODES.GINGERBREAD_MR1) {
				if(isNextDate){
					datePickerDialog.getDatePicker().setMinDate(TIME_MIN);
					if(!notSetMaxBackDate)
						datePickerDialog.getDatePicker().setMaxDate(Calendar.getInstance().getTimeInMillis());
				}else
					if(!notSetMaxBackDate)
						datePickerDialog.getDatePicker().setMaxDate(TIME_MAX);
			}
		}
		
		return datePickerDialog;
	}

	public void onDateSet(DatePicker view, int year, int month, int day) {
		Calendar c = Calendar.getInstance();
		c.set(year, month, day, 0, 0, 0);
		if(isNextDate)
			TIME_MAX = c.getTimeInMillis();
		else
			TIME_MIN = c.getTimeInMillis();
		mParent.setTimeMin(TIME_MIN, TIME_MAX);
		if(isNextDate)
			mParent.setNextDate(year, month, day);
		else
			mParent.setBackDate(year, month, day);
	}

	public boolean isNotSetMaxBackDate() {
		return notSetMaxBackDate;
	}

	public void setNotSetMaxBackDate(boolean notSetMaxBackDate) {
		this.notSetMaxBackDate = notSetMaxBackDate;
	}
	
	

}
